<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请选择工厂"
            clearable
          >
            <el-option
              v-for="item in plants"
              :key="item.plantId"
              :label="item.plantName"
              :value="item.plantId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物料号">
          <el-input
            v-model="searchParam.materialNumber"
            placeholder="请输入物料号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="计划到货日期">
          <el-date-picker
            v-model="searchParam.arriveDateSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            @change="getarriveDate"
          />
        </el-form-item>
        <el-form-item label="采购计划状态">
          <el-select
            clearable
            v-model="searchParam.orderScheduleState"
            placeholder="请输入采购周期类型"
            style="width: 250px"
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList(
                'OrderScheduleState'
              )"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商id" style="display: none">
          <el-input
            v-model="searchParam.partnerId"
            placeholder="请输入采购计划状态"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="primary"
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          批量反馈
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="工厂号"
          prop="plantCode"
          min-width="100"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="工厂名"
          prop="plantName"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          label="计划协议号"
          prop="purchasePlanNumber"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料号"
          prop="materialNumber"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料名"
          prop="materialName"
          min-width="150"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="计划到货日期"
          prop="arriveDate"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="计划采购数量"
          prop="planQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
        />
        <el-table-column
          label="可满足数量"
          prop="agreeQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
        />
        <el-table-column
          label="反馈时间"
          prop="replyTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              :disabled="
                scope.row.replyTime != '' && scope.row.replyTime != null
              "
            >
              反馈
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="deliverData(scope.row)"
            >
              生成发货数据
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <srmorderfeedbackdule-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { ElOption, ElSelect } from "element-plus";

const dictionaryStore = useDictStoreHook();
defineOptions({
  name: "SRMSRMPLANFEEDBACK",
  inheritAttrs: false,
});
// 工厂
let plants = ref([]);
// 请求参数
const requestApi = "/srm/partner/srmorderfeedback/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};
// 表单内容
let formData = reactive({
  id: "",
  packageCommandId: "",
  orderNo: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  purchasePlanNumber: "",
  partnerId: "",
  partnerCode: "",
  materialId: "",
  materialNumber: "",
  materialName: "",
  storageLocationId: "",
  storageLocationCode: "",
  storageLocationName: "",
  agreeQuantity: "",
  replyTime: "",
  packingMaterialId: "",
  packingMaterialCode: "",
  packingMaterialName: "",
});
/** 重置表单 */
function resetForm() {
  formData.id = "";
  formData.orderNo = "";
  formData.packageCommandId = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.purchasePlanNumber = "";
  formData.partnerId = "";
  formData.partnerCode = "";
  formData.materialId = "";
  formData.materialNumber = "";
  formData.materialName = "";
  formData.storageLocationId = "";
  formData.storageLocationCode = "";
  formData.storageLocationName = "";
  formData.agreeQuantity = "";
  formData.replyTime = "";
  formData.packingMaterialId = "";
  formData.packingMaterialCode = "";
  formData.packingMaterialName = "";
}
// 选择器
let packageCmds = ref([]);
// 初始化搜索参数数据
const searchParamInit = {
  plantName: "",
  materialNumber: "",
  arriveDateSearch: [],
  arriveDateStart: "",
  arriveDateEnd: "",
  orderScheduleState: "",
  partnerId: "",
};

const feedbackParam = {
  api: "/srm/partner/srmorderfeedback/feedback",
  data: {},
};
const rules = reactive({
  packageCommandId: [
    { required: true, message: "包装指令", trigger: "change" },
  ],
});
const formRef = ref(ElForm);
// 数据请求错误后处理
function requestError() {}

function dataCallBack(res: any[]) {
  for (let i = 0; i < res.length; i++) {
    res[i].arriveDate = formatDate(res[i].arriveDate);
  }
  return res;
}

function formatDate(date: any) {
  let d = new Date(date),
    month = "" + (d.getMonth() + 1),
    day = "" + d.getDate(),
    year = d.getFullYear();

  if (month.length < 2) month = "0" + month;
  if (day.length < 2) day = "0" + day;

  return [year, month, day].join("-");
}

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  // handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  feedbackParam
);

onMounted(() => {
  //todo 通过权限获取登陆人供应商id getLoginInfo();
  getPartnerPlants("1744249727643115521");

  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

/** 查询详情 */
async function getInfo(id: string) {
  request({
    url: `/srm/partner/srmorderfeedback/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      // console.log(res);
    });
}

/** 预留权限请求 */
async function getLoginInfo() {
  request({
    url: `获取权限`,
    method: "post",
  }).then((data) => {
    // todo  searchParam.value.partnerId = data.data 查询条件添加供应商id
    //根据供应商id查询该供应商与工厂的计划
    getPartnerPlants(data.data);
  });
}

/** 根据供应商id查询合作的工厂*/
async function getPartnerPlants(id: string) {
  // todo 一下两列临时存放第一个编辑后重置页面搜索内容(不重置登陆人id),第二个供应商id赋值 每次查询带上当条件
  searchParamInit.partnerId = id;
  searchParam.value.partnerId = id;

  request({
    url: `/srm/partner/srmorderfeedback/plant/${id}`,
    method: "get",
  }).then((data) => {
    plants.value = data.data;
  });
}

/** 打开订货计划表单弹窗 */
function openDialog(roleObj: Object) {
  addDialog.title = "订单要货数量反馈";
  getInfo(roleObj.id);
  addDialog.readvisible = false;
}

/** 打开订货计划表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "订货计划详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getarriveDate(data: any) {
  if (data) {
    searchParam.value.arriveDateStart = data[0];
    searchParam.value.arriveDateEnd = data[1];
  } else {
    searchParam.value.arriveDateStart = "";
    searchParam.value.arriveDateEnd = "";
  }
}

/**批量反馈提醒*/
const handleTableDelete = (dictId?: number) => {
  if (feedbackParam?.api) {
    const dictIds = [dictId || ids].join(",");
    if (!dictIds) {
      ElMessage.warning("请勾选删除项");
      return;
    }
    ElMessageBox.alert("确定要对选中要货信息反馈?", "批量反馈", {
      confirmButtonText: "可以满足供货",
    }).then(async () => {
      openGoods();
    });
  } else {
    return;
  }
};
/**生成发货数据警告弹框*/
const deliverData = (row: any) => {
  ElMessageBox.confirm(
    "确定要对选中要货生成发货数据?生成后既默认可满足供货需求，不可更改!",
    "生成发货数据",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    }
  )
    .then(() => {
      packageCmds.value = [];
      request({
        url: `srm/partner/srmorderfeedback/createUnitData`,
        method: "post",
        data: { ...row, packageCommandId: "" },
      }).then((data) => {
        if (data.data == null && data.code == 200) {
          ElMessage.success("生成包装成功");
        }
        if (data.data.length > 1) {
          packageCmds.value = data.data;
          selectCmd(row);
        }
      });
    })
    .catch(() => {});
};

/**批量反馈数量填写*/
const openGoods = () => {
  ElMessageBox.prompt("可满足数量", "反馈供货数量", {
    confirmButtonText: "确认",
    inputPattern: /^[1-9]\d*$/,
    inputErrorMessage: "请输入正确数量",
  }).then(async ({ value }) => {
    // data.agreeQuantity = value;
    await request({
      url: feedbackParam.api,
      method: "post",
      data: { ids: ids.value, agreeQuantity: value },
    })
      .then(() => {
        ElMessage.success("反馈成功");
        // reset();
        getTableList();
      })
      .finally(() => {});
  });
};

/** 选择指令消息框，下拉列表形式*/
const selectCmd = (row: any) => {
  const selectOptions = () => {
    return packageCmds.value.map((item) =>
      h(ElOption, { label: item.packageCommandName, value: item.id })
    );
  };
  const selectedPackageCommandId = ref("");
  const select = () =>
    h("p", null, [
      h("span", null, "此物料的包装指令有多个，请选择需要打包的包装指令"),
      h(
        ElSelect,
        {
          modelValue: selectedPackageCommandId.value,
          placeholder: "请选择",
          "onUpdate:modelValue": (val) => {
            selectedPackageCommandId.value = val;
          },
        },
        selectOptions
      ),
    ]);

  ElMessageBox({
    title: "提示",
    message: select,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    beforeClose: (action, instance, done) => {
      if (action === "confirm") {
        if (!selectedPackageCommandId.value) {
          ElMessage.error("未选择包装指令");
          return;
        } else {
          done();
        }
      } else {
        done();
      }
    },
  }).then((data) => {
    request({
      url: `srm/partner/srmorderfeedback/createUnitData`,
      method: "post",
      data: { ...row, packageCommandId: selectedPackageCommandId.value },
    }).then((data) => {
      ElMessage.success("生成包装成功");
    });
  });
};
</script>
